package com.whty.cms.filewps.upload.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.whty.cms.filewps.common.constants.Consts;
import com.whty.cms.filewps.common.model.MsgAttachment;
import com.whty.cms.filewps.common.model.MsgRetAttachement;
import com.whty.cms.filewps.common.model.MsgTransform;
import com.whty.cms.filewps.common.model.TransformJobError;
import com.whty.cms.filewps.common.service.MongoService;
import com.whty.cms.filewps.common.service.impl.BaseAbstractServiceImpl;
import com.whty.cms.filewps.upload.dao.AttachFileMapper;
import com.whty.cms.filewps.upload.dao.TransformJobMapper;
import com.whty.cms.filewps.upload.dto.AttachFile;
import com.whty.cms.filewps.upload.dto.TransformJob;
import com.whty.cms.filewps.upload.service.IFileService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * Created by Administrator on 2019/3/1 0001.
 */
@Service("fileService")
public class FileServiceImpl extends BaseAbstractServiceImpl<AttachFile> implements IFileService {
    private static final Logger LOG = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private MongoService mongoService;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    /**
     * 批量插入数据入库和ES
     * @return
     */
    @Override
    public boolean saveCmqMessage(JSONArray data) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);//关闭session的自动提交
        boolean flag = true;
        try {
            AttachFileMapper attachFileMapper = session.getMapper(AttachFileMapper.class);
            TransformJobMapper transformJobMapper = session.getMapper(TransformJobMapper.class);
            for(int i = 0 ; i < data.size(); i++) {
                JSONObject d = JSONUtil.parseObj(data.get(i).toString());
                String tableType = (String) d.remove(Consts.TABLE_TYPE);
                d.remove(Consts.TABLE_TYPE);
                if(tableType.equals(Consts.TABLE_ATTACHMENT)) {
                    //附件数据
                    LOG.info("附件数据信息：{}" , d.toString());
                    MsgAttachment msgAttachment = JSONUtil.toBean(d,MsgAttachment.class);
                    AttachFile attachFile = new AttachFile();
                    BeanUtils.copyProperties(msgAttachment, attachFile);
                    AttachFile model = attachFileMapper.selectByPrimaryKey(attachFile.getFid());
                    if(null != model) {
                        LOG.info("附件表中存在相同的主键-------> fid: {}", model.getFid());
                        continue;
                    }

                    //判断MD5的值是否正确,若不正常赋值为null
                    String md5 = attachFile.getFileMd5();
                    if(! (md5.length() <= 32)) {
                        attachFile.setFileMd5("");
                    }

                    if(StringUtils.isEmpty(attachFile.getNeedTransform())) {
                        attachFile.setNeedTransform("1");
                    }
                    attachFileMapper.insert(attachFile);
                }
                if(tableType.equals(Consts.TABLE_TRANSFORM)) {
                    //转码信息
                    LOG.info("转码数据信息：{}" , d.toString());
                    MsgTransform msgTransform = JSONUtil.toBean(d,MsgTransform.class);
                    TransformJob transformJob = new TransformJob();
                    BeanUtils.copyProperties(msgTransform, transformJob);
                    TransformJob model = transformJobMapper.selectByPrimaryKey(transformJob.getTransformId());
                    if(null != model) {
                        LOG.info("转码表中存在相同的主键-------> transformId: {}", model.getTransformId());
                        continue;
                    }
                    transformJobMapper.insert(transformJob);
                }
            }
            session.commit();
            session.clearCache();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
            flag = false;
        } finally{
            session.close();
        }
        return flag;
    }

    @Override
    public boolean updateFileData(MsgRetAttachement msgRetAttachement) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(false);//关闭session的自动提交
        boolean flag = true;
        try {
            //ES中数据维护又回调接口维护
            /*AttachFileMapper attachFileMapper = session.getMapper(AttachFileMapper.class);
            Example example = new Example(AttachFile.class);
            example.createCriteria().andEqualTo("transformId",msgRetAttachement.getTransformId());
            List<AttachFile> attaches = attachFileMapper.selectByExample(example);
            if(attaches != null && attaches.size() > 0 )  {
                for(AttachFile attache : attaches) {
                    Long fid = attache.getFid();
                    //根据fid修改ES中的数据中的数据
                    net.sf.json.JSONObject fileInfo = EsUtil.searchDoc(String.valueOf(fid));
                    fileInfo.put("transformStutas", msgRetAttachement.getTransformStatus());  //转码完成
                    fileInfo.put("transFileLength", msgRetAttachement.getTransFileLength());
                    fileInfo.put("previewUrl", msgRetAttachement.getPreviewUrl());
                    fileInfo.put("duration", msgRetAttachement.getDuration());
                    fileInfo.put("thumbnailUrl", msgRetAttachement.getThumnailUrl());
                    EsUtil.addOrUpdateDoc(String.valueOf(fid), fileInfo.toString());
                }
            } else {
                throw new BusinessException("[FileServiceImpl#updateFileData] : " + "获取attacheFile数据为null:" + "transformId为" + msgRetAttachement.getTransformId());
            }*/

            //根据transformId修改数据库转码表中的数据
            TransformJobMapper transformJobMapper = session.getMapper(TransformJobMapper.class);
            TransformJob model = transformJobMapper.selectByPrimaryKey(msgRetAttachement.getTransformId());
            if(null == model) {
                TransformJobError transformJobError = new TransformJobError();
                BeanUtil.copyProperties(msgRetAttachement, transformJobError);
                mongoService.insert(transformJobError);
                return flag;
                //throw new BusinessException("[FileServiceImpl#updateFileData] : " + "获取TransformJob数据为null:" + "transformId为" + msgRetAttachement.getTransformId());
            }
            TransformJob transformJob = new TransformJob();
            transformJob.setTransformId(msgRetAttachement.getTransformId());
            transformJob.setPreviewUrl(msgRetAttachement.getPreviewUrl());
            transformJob.setTransformStatus(msgRetAttachement.getTransformStatus());
            transformJob.setThumnailUrl(msgRetAttachement.getThumnailUrl());
            transformJob.setTransFileLength(Long.valueOf(msgRetAttachement.getTransFileLength()));
            transformJob.setDuration(Integer.valueOf(msgRetAttachement.getDuration()));
            transformJobMapper.updateByPrimaryKeySelective(transformJob);
            session.commit();
            session.clearCache();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
            flag = false;
        } finally{
            session.close();
        }
        return flag;
    }
}
